import { Table, Space, Button, Modal, message } from 'antd';
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { getOrderList, deleteOrder } from '../../services/order';
const { confirm } = Modal;

export default function Order() {
  const [list, setList] = useState([]);
  const navigate = useNavigate();

  const columns = [
    {
      title: '订单ID',
      dataIndex: 'orderId',
      key: 'orderId',
      render: (text) => (
        <Button type="link" onClick={() => navigate('/order/' + text)}>
          {text}
        </Button>
      ),
    },
    {
      title: '用户ID',
      dataIndex: 'userId',
      key: 'userId',
    },
    {
      title: '金额',
      dataIndex: 'cost',
      key: 'cost',
    },
    {
      title: '优惠',
      dataIndex: 'discount',
      key: 'discount',
    },
    {
      title: '运费',
      dataIndex: 'shippingCost',
      key: 'shippingCost',
    },
    {
      title: '提交时间',
      dataIndex: 'submitTime',
      key: 'submitTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
          <Space size="middle">
            <Button type="primary" onClick={() => navigate('/order/edit/' + record.orderId)}>修改</Button>
            <Button type="danger" onClick={() => handleDelete(record.orderId)}>删除</Button>
          </Space>
      ),
    },
  ];

  useEffect(() => {
    fetchOrderList();
  }, []);

  const fetchOrderList = () => {
    getOrderList().then((response) => {
      console.log(response.data);
      setList(response.data.result);
    });
  };

  const handleClick = () => {
    navigate('/order/add');
  };

  const handleDelete = (id) => {
    confirm({
      title: '确认删除吗',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        return deleteOrder(id).then((response) => {
          const { code, msg } = response.data;
          if (code === 1) {
            message.success(msg);
            fetchOrderList();
          }
        });
      },
    });
  };

  return (
    <>
      <Button type="primary" onClick={handleClick} style={{ marginBottom: 15 }}>
        新增
      </Button>
      <Table rowKey="orderId" dataSource={list} columns={columns} />
    </>
  );
}
